package com.edgar.refactor;

public class PrimeGenerate {
    
    private static int a;
    private static boolean[] f;
    private static int[] result;

    public static int[] generatePrimes(int maxValue) {
        if (maxValue >= 2) {
            initializeArrayOfIntegers(maxValue);
            
            crossOutMultiples();
            
            loadPrimes();
            return result;
        }
        return new int[0];
    }

    private static void loadPrimes() {
        int i;
        int j;
        //统计
        int count = 0;
        for (i = 0; i < a; i ++) {
            if (f[i]) {
                count ++;
            }
        }
        
        //结果集
        result = new int[count];
        
        for (i = 0, j = 0; i < a; i ++) {
            if (f[i]) {
                result[j ++] = i;
            }
        }
    }

    private static void crossOutMultiples() {
        //判断是否是素数
        for(int i = 2; i < Math.sqrt(a) + 1; i ++) {
            for (int j = 2 * i; j < a; j += i) {
                f[j] = false;
            }
        }
    }

    private static void initializeArrayOfIntegers(int maxValue) {
        //声明
        f = new boolean[maxValue + 1];
        
        //0,1不是素数
        f[0] = f[1] = false;
        //初始化
        for (int i = 2; i < f.length; i++) {
            f[i] = true;
        }
        
    }
}
